package com.kyzh.core.pager.home.homesearch

import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.gushenge.atools.util.AView
import com.gushenge.atools.util.setHeight
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.Game
import com.gushenge.core.beans.Text
import com.gushenge.core.impls.SearchImpl
import com.gushenge.core.listeners.ResultListener
import com.kyzh.core.R
import com.kyzh.core.adapters.SearchHistoryAdapter
import com.kyzh.core.utils.*
import kotlinx.android.synthetic.main.act_search.*
import org.litepal.LitePal
import org.litepal.extension.find
import com.gushenge.core.toast

/**
 * Created by Administrator on 2017/9/19 0019.
 */

class SearchActivity : BaseActivity() {

    lateinit var adapter:SearchHistoryAdapter
    val historys = mutableListOf<Text>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_search)

        initView()
    }

    private fun initView() {
        search_root.setHeight(dip(44)+AView.getStatusBarHeight(this@SearchActivity))
        search_close.setOnClickListener { finish() }
        edittext.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                /*隐藏软键盘*/
                val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                if (imm.isActive) imm.hideSoftInputFromWindow(v.applicationWindowToken, 0)
                val words = edittext.text.toString().trim()
                if (words.isNotEmpty()) {
                    LitePal.deleteAll(Text::class.java,"name = ?",words)
                    Text(words).save()
                    SearchImpl().search(words, object : ResultListener {
                        override fun success(bean: Any) {
                            bean as ArrayList<Game>
                            if (bean.size==1){
                                startGameDetailActivity(bean[0].gid)
                            }else{
                                startActivity<SearchArrActivity>("text" to words)
                            }
                        }

                        override fun error(error: String) {
                            error.toast()
                        }
                    })
                    edittext.text.clear()
                }
            }
            true
        }
        tvSearch.setOnClickListener {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (imm.isActive) imm.hideSoftInputFromWindow(it.applicationWindowToken, 0)
            val words = edittext.text.toString().trim()
            if (words.isNotEmpty()) {
                LitePal.deleteAll(Text::class.java,"name = ?",words)
                Text(words).save()
                SearchImpl().search(words, object : ResultListener {
                    override fun success(bean: Any) {
                        bean as ArrayList<Game>
                        if (bean.size==1){
                            startGameDetailActivity(bean[0].gid)
                        }else{
                            startActivity<SearchArrActivity>("text" to words)
                        }
                    }

                    override fun error(error: String) {
                        error.toast()
                    }
                })
                edittext.text.clear()
            }
        }
        hideViews()
        val manager = object :FlexboxLayoutManager(this@SearchActivity){
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        manager.flexDirection = FlexDirection.ROW
        manager.flexWrap = FlexWrap.WRAP
        history.layoutManager = manager
        adapter = SearchHistoryAdapter(R.layout.act_search_item,historys,true)
        history.adapter = adapter

        addHot()

        delete.setOnClickListener {
            LitePal.deleteAll(Text::class.java)
            searchText()
        }
        adapter.setOnItemLongClickListener { adapter, view, position ->
            vibrate(100)
            LitePal.deleteAll(Text::class.java, "name=?", historys[position].name)
            searchText()
            true
        }
    }

    private fun hideViews() {
        history.visibility = View.GONE
        tips.visibility = View.GONE
        history_title.visibility = View.GONE
    }

    private fun addHot() {
        SearchImpl().hot(object : ResultListener {
            override fun success(beans: Any) {
                beans as ArrayList<Text>
                val hots = mutableListOf<Text>()
                hots.addAll(beans)
                val layoutManager = object :FlexboxLayoutManager(this@SearchActivity){
                    override fun canScrollVertically(): Boolean {
                        return false
                    }
                }
                layoutManager.flexDirection = FlexDirection.ROW
                layoutManager.flexWrap = FlexWrap.WRAP
                hot.layoutManager = layoutManager
                hot.adapter = SearchHistoryAdapter(R.layout.act_search_item,hots,false)
                searchText()
            }

            override fun error() {
                hot.visibility = View.GONE
                hot_title.visibility = View.GONE
            }
        })
    }

    override fun onRestart() {
        super.onRestart()
        searchText()
    }

    fun searchText() {
        historys.clear()
        val map = LitePal.order("id desc").find<Text>()
        if (map.isNullOrEmpty()){
            history.visibility = View.GONE
            tips.visibility = View.GONE
            history_title.visibility = View.GONE
        }else{
            history.visibility = View.VISIBLE
            tips.visibility = View.VISIBLE
            history_title.visibility = View.VISIBLE
            historys.addAll(map)
            adapter.notifyDataSetChanged()
        }
    }
}